package org.zongf.learn.grpc.starter.core;

import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.Data;
import org.springframework.context.ApplicationContext;
import org.zongf.learn.grpc.starter.anno.GrpcClient;
import org.zongf.learn.grpc.starter.base.BaseFactoryBean;
import org.zongf.learn.grpc.starter.config.GrpcClientConfig;

import java.lang.reflect.Method;

/** ProxyComponent 动态代理生成工厂 <br/>
 *     1) FactoryBean 中不能使用@Autowired 注入spring组件, 需要借助于 ApplicationContextAware 接口
 * @author zongf
 * @since 2020-11-26
 */
@Data
public class GrpcClientFactoryBean extends BaseFactoryBean {

    private  Class<? extends GrpcClient> grpcStubClass;

    private String serviceName;

    private ApplicationContext applicationContext;

    @Override
    public Object getObject() throws Exception {
        GrpcClientConfig grpcClientConfig = this.applicationContext.getBean(GrpcClientConfig.class);


        Class<?> rpcService = grpcStubClass.getDeclaringClass();


        Method newBlockingStub = rpcService.getMethod("newBlockingStub", Channel.class);

        String hostInfo = grpcClientConfig.getClient().get(serviceName);

        String[] array = hostInfo.split(":");

        String host = array[0];
        Integer port = Integer.parseInt(array[1]);

        ManagedChannel managedChannel = ManagedChannelBuilder
                .forAddress(host, port)
                .usePlaintext()
                .build();

        return newBlockingStub.invoke(null, managedChannel);
    }

}
